using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
using eShop.Utility;


namespace Entity
{
    /// <summary>
    /// This object represents the Private Fields of TblNewsletterGroup.
    /// </summary>

    [System.ComponentModel.DataObject]
    public class TblNewsletterGroup : DatabaseUtility
    {
        #region TblNewsletterGroup Private Fields


        Int32 _newsletterGroupId;
        String _newsletterGroupName = String.Empty;
        Boolean _isActive;

        #endregion
        #region TblNewsletterGroup Constractor
        /// <summary>
        /// Creates an empty object of TblNewsletterGroup. 
        /// This is mainly used to create a new instance of TblNewsletterGroup to add a new TblNewsletterGroup.
        /// </summary>
        public TblNewsletterGroup() { }


        /// <summary>
        /// Used to retrieve employee information from database, 
        /// which is also used by Update method to save information of an existing TblNewsletterGroup.
        /// </summary>
        public TblNewsletterGroup
        (
            Int32 newsletterGroupId,
            String newsletterGroupName,
            Boolean isActive
        )
        {
            _newsletterGroupId = newsletterGroupId;
            _newsletterGroupName = newsletterGroupName;
            _isActive = isActive;
        }

        #endregion
        #region TblNewsletterGroup Properties

        /***********************************************************************************************
                                    -- PROPERTIES --        
         Contains all the properties representing the data fields of the current entity.
         ***********************************************************************************************/

        /// <summary>
        /// This is the Primary key value of the NewsletterGroupId, which can't be assigned from the application,
        /// to ensure the data consistancy, by not letting the user to change the PK_TblNewsletterGroup to update the data of an another TblNewsletterGroup instance.
        /// For view or updation purpose, every TblNewsletterGroup will be retrieved thru the proper 'Get' method.
        /// </summary>

        public Int32 NewsletterGroupId
        {
            get { return _newsletterGroupId; }
        }


        public String NewsletterGroupName
        {
            get { return _newsletterGroupName; }
            set { _newsletterGroupName = value; }
        }

        public Boolean IsActive
        {
            get { return _isActive; }
            set { _isActive = value; }
        }


        #endregion
        #region TblNewsletterGroup Static Methods
        /************************************************************************************
                                    -- CREATE METHOD (STATIC) --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        Note 1:
        This method is specially useful for the case, where we need to use Object Data Source controls.
        For ObjectDataSource/SqlDataSource controls, the insert/update metnod requires paramters methods, rather property based methods.
        However, there is still a way to pass property based objects as method parameter for data source controls, 
        but in that case we could not use Sql type, as view controls or asp parameter control can only contain few of primitive type.
        The main reason to remain the Sql Type in our object architecture is it is faster and contains better way for null value support.
        
        Note 2: 
        Non-primary key: it should be primitive type, as the asp paramter control (included in data source control) supports only primitive types.
        /*****************************************************************************/
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
        public static Int32 CreateNewTblNewsletterGroup
        (
            String newsletterGroupName,
            Boolean isActive
        )
        {
            //creating an empty TblNewsletterGroup object
            TblNewsletterGroup tblNewsletterGroup = new TblNewsletterGroup();
            tblNewsletterGroup.NewsletterGroupName = newsletterGroupName;
            tblNewsletterGroup.IsActive = isActive;

            return TblNewsletterGroup.CreateNewTblNewsletterGroup(tblNewsletterGroup);
        }

        /************************************************************************************
                 -- UPDATE METHODS (STATIC) --
        *************************************************************************************/

        /************************* Architecure note:**********************************
        Note 1:
        This method is specially useful for the case, where we need to use Object Data Source controls.
        For ObjectDataSource/SqlDataSource controls, the insert/update metnod requires paramters methods, rather property based methods.
        However, there is still a way to pass property based objects as method parameter for data source controls, 
        but in that case we could not use Sql type, as view controls or asp parameter control can only contain few of primitive type.
        The main reason to remain the Sql Type in our object architecture is it is faster and contains better way for null value support.
        
        Note 2: 
        There the two types of paramaters will be passed here.
         * a. Primary key paramater: it should be Sql type, as we will bind the primary key property for the view controls (form view, details view etc) as datakey.
         * b. Non-primary key: it should be primitive type, as the asp paramter control (included in data source control) supports only primitive types.
        /*****************************************************************************/

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool UpdateTblNewsletterGroup
        (
            Int32 newsletterGroupId,
            String newsletterGroupName,
            Boolean isActive
        )
        {
            TblNewsletterGroup tblNewsletterGroup = TblNewsletterGroup.GetTblNewsletterGroupByNewsletterGroupId(newsletterGroupId);

            tblNewsletterGroup.NewsletterGroupName = newsletterGroupName;
            tblNewsletterGroup.IsActive = isActive;

            return TblNewsletterGroup.UpdateTblNewsletterGroup(tblNewsletterGroup);
        }

        /************************************************************************************
                         -- DELETE METHODS --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        We have used the employeeId parameter as SqlInt32, to bind the delete method with object data source and view control directly.
        ****************************************************************************/
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool DeleteTblNewsletterGroup
        (
            Int32 newsletterGroupId
        )
        {
            //Validate Input
            if (newsletterGroupId <= GetNewsletterGroupIdMinValue)
                throw (new ArgumentOutOfRangeException("newsletterGroupId"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@NewsletterGroupId", SqlDbType.Int, 0, ParameterDirection.Input, newsletterGroupId);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERGROUP_DELETETBLNEWSLETTERGROUP);
            ExecuteScalarCmd(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);

        }

        /// <summary>
        /// Deletes a set of employees from the database.
        /// </summary>
        public static bool DeleteTblNewsletterGroupList(System.Collections.Generic.List<Int32> newsletterGroupIdListToDelete)
        {
            //Validate Input
            foreach (Int32 newsletterGroupId in newsletterGroupIdListToDelete)
                if (newsletterGroupId <= GetNewsletterGroupIdMinValue)
                    throw (new ArgumentOutOfRangeException("newsletterGroupId"));

            //performing deletion operation //

            string xmlString = FormatXMLForIdArray(newsletterGroupIdListToDelete);

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@NewsletterGroupIdList", SqlDbType.Xml, xmlString.ToString().Length, ParameterDirection.Input, xmlString.ToString());
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERGROUP_DELETETBLNEWSLETTERGROUPLIST);
            ExecuteScalarCmd(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == newsletterGroupIdListToDelete.Count ? true : false);
        }

        /************************************************************************************
                                 -- GET BY PRIMARY METHODS --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        Retrives an Employee from database, based on it's primary key.
        To view or update an employee, everytime we must have to use this type of 'get' method, 
        since we don't have direct access to the Primary key value for assigning value.
        We have used the employeeId parameter as SqlInt32, to bind the delete method with object data source and view control directly.
        /*****************************************************************************/
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static TblNewsletterGroup GetTblNewsletterGroupByNewsletterGroupId(Int32 newsletterGroupId)
        {
            if (newsletterGroupId <= GetNewsletterGroupIdMinValue)
                throw (new ArgumentOutOfRangeException("newsletterGroupId"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@NewsletterGroupId", SqlDbType.Int, 0, ParameterDirection.Input, newsletterGroupId);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERGROUP_GETTBLNEWSLETTERGROUPBYNEWSLETTERGROUPID);
            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblNewsletterGroupCollectionFromReader);
            List<TblNewsletterGroup> objCollection = ((List<TblNewsletterGroup>)ExecuteReaderCmd(sqlCmd, test));

            if (objCollection.Count > 0)
                return objCollection[0];
            else
                return null;
        }

        /************************************************************************************
                         -- GET BY FOREIGN KEY METHODS --
        *************************************************************************************/

        /************************************************************************************
                 -- GET ALL METHODS --
        *************************************************************************************/
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static List<TblNewsletterGroup> GetAllTblNewsletterGroup()
        {

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERGROUP_GETALLTBLNEWSLETTERGROUP);
            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblNewsletterGroupCollectionFromReader);
            List<TblNewsletterGroup> objCollection = ((List<TblNewsletterGroup>)ExecuteReaderCmd(sqlCmd, test));

            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static List<TblNewsletterGroup> GetAllTblNewsletterGroupPaged(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            //Validate Input
            if (orderBy == "")
                orderBy = "NewsletterGroupId";

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@orderby", SqlDbType.VarChar, 50, ParameterDirection.Input, orderBy);
            AddParameterToSqlCmd(sqlCmd, "@startrow", SqlDbType.Int, 0, ParameterDirection.Input, startRowIndex);
            AddParameterToSqlCmd(sqlCmd, "@pagesize", SqlDbType.Int, 0, ParameterDirection.Input, maximumRows);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERGROUP_GETALLTBLNEWSLETTERGROUPPAGED);

            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblNewsletterGroupCollectionFromReader);
            List<TblNewsletterGroup> objCollection = ((List<TblNewsletterGroup>)ExecuteReaderCmd(sqlCmd, test));
            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static int GetAllTblNewsletterGroupPagedCount(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();

            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERGROUP_GETALLTBLNEWSLETTERGROUPPAGEDCOUNT);
            ExecuteScalarCmd(sqlCmd);

            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return returnValue;
        }

        #endregion
        #region Employee Instance Methods
        /************************************************************************************
                                    -- SAVE (INSERT/UPDATE) METHODS (INSTANCE) --
        *************************************************************************************/
        /// <summary>
        /// Saves (inserts and updates) an Employee into database.
        /// The insertion occur if the EmployeeId conatins default value.
        /// Otherwises it updates the Employee into the database, based on the primary key value stored in EmployeeId.
        /// This technique ensures an Employee will not be updated without having a valid EmployeeId.
        /// </summary>
        public bool Save()
        {
            if (NewsletterGroupId <= GetNewsletterGroupIdMinValue)
            {
                Int32 TempId = CreateNewTblNewsletterGroup(this);
                if (TempId > 0)
                {
                    _newsletterGroupId = TempId;
                    return true;
                }
                else
                {
                    // error occurs
                    return false;
                }
            }
            else
            {	//This is a update Command
                return (UpdateTblNewsletterGroup(this));
            }

        }

        public static Int32 CreateNewTblNewsletterGroup(TblNewsletterGroup newTblNewsletterGroup)
        {
            // validate Parameters
            if (newTblNewsletterGroup == null)
                throw (new ArgumentNullException("newTblNewsletterGroup"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            int length = 0;
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@NewsletterGroupName", SqlDbType.VarChar, 500, ParameterDirection.Input, newTblNewsletterGroup.NewsletterGroupName);
            AddParameterToSqlCmd(sqlCmd, "@IsActive", SqlDbType.Bit, 0, ParameterDirection.Input, newTblNewsletterGroup.IsActive);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERGROUP_CREATENEWTBLNEWSLETTERGROUP);
            ExecuteScalarCmd(sqlCmd);
            return (Int32.Parse(sqlCmd.Parameters["@ReturnValue"].Value.ToString()));

        }
        /// <summary>
        /// Updates an TblNewsletterGroup instance to the database.
        /// </summary>
        public static bool UpdateTblNewsletterGroup(TblNewsletterGroup newTblNewsletterGroup)
        {
            // validate Parameters
            if (newTblNewsletterGroup == null)
                throw (new ArgumentNullException("newTblNewsletterGroup"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            int length = 0;
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@NewsletterGroupId", SqlDbType.Int, 0, ParameterDirection.Input, newTblNewsletterGroup.NewsletterGroupId);
            AddParameterToSqlCmd(sqlCmd, "@NewsletterGroupName", SqlDbType.VarChar, 500, ParameterDirection.Input, newTblNewsletterGroup.NewsletterGroupName);
            AddParameterToSqlCmd(sqlCmd, "@IsActive", SqlDbType.Bit, 0, ParameterDirection.Input, newTblNewsletterGroup.IsActive);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERGROUP_UPDATETBLNEWSLETTERGROUP);
            ExecuteScalarCmd(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);
        }
        #endregion

        #region TblNewsletterGroup Related Collections
        /// <summary>
        /// Creates and returns a strongly typed collection of Employee custom entity. 
        /// The colelction is created through iterating on the IdataReader object which contains Employee information, as a set of records, similar to tabular format.
        /// </summary>
        public static IList GenerateTblNewsletterGroupCollectionFromReader(IDataReader returnData)
        {

            //creating the instance of Employee collection
            List<TblNewsletterGroup> colTblNewsletterGroup = new List<TblNewsletterGroup>();

            /************************* Architecure note:**********************************
             * Below code includes the null value functionality to retieve the data which has nill value in database end.
             * Design consideration:
             * Besides general data fields, special care should be taken for primary keys, to assign '0'/defaultvalue, rather passing 'Null' value in constructor parameter.
             * Although we are considering sqldb tyoe data for the current data container, but while retireving data from database end, through datareader object, we need to cast data reader objects using .net primitive data type, 
             * rather using sqldb type to cast, since data reader objects don't support sql db type to be casted.
             *****************************************************************************/

            //Iterating thriugh the data reader, to generate Employee collection.

            //getting the Employee collection by iterating thru the data reader
            while (returnData.Read())
            {
                //passing the TblNewsletterGroup constructor parameters from the current instance of data reader fields.
                TblNewsletterGroup newTblNewsletterGroup = new TblNewsletterGroup
                (
                    returnData["NewsletterGroupId"] == System.DBNull.Value ? GetNewsletterGroupIdMinValue : (Int32)returnData["NewsletterGroupId"],
                    returnData["NewsletterGroupName"] == System.DBNull.Value ? string.Empty : (String)returnData["NewsletterGroupName"],
                    returnData["IsActive"] == System.DBNull.Value ? false : (Boolean)returnData["IsActive"]

                );
                //adding the Employee to the collection
                colTblNewsletterGroup.Add(newTblNewsletterGroup);
            }

            //returns the collection of Companys 
            return (colTblNewsletterGroup);
        }

        #endregion
        #region Constants and Default Values

        public static Int32 GetNewsletterGroupIdMinValue
        {
            get
            {
                return 0;
            }
        }

        //create method related contants
        internal const string SPR_TBLNEWSLETTERGROUP_CREATENEWTBLNEWSLETTERGROUP = "spr_TblNewsletterGroup_CreateNewTblNewsletterGroup";
        internal const string SPR_TBLNEWSLETTERGROUP_UPDATETBLNEWSLETTERGROUP = "spr_TblNewsletterGroup_UpdateTblNewsletterGroup";
        internal const string SPR_TBLNEWSLETTERGROUP_DELETETBLNEWSLETTERGROUP = "spr_TblNewsletterGroup_DeleteTblNewsletterGroup";
        internal const string SPR_TBLNEWSLETTERGROUP_DELETETBLNEWSLETTERGROUPLIST = "spr_TblNewsletterGroup_DeleteTblNewsletterGroupList";
        internal const string SPR_TBLNEWSLETTERGROUP_GETTBLNEWSLETTERGROUPBYNEWSLETTERGROUPID = "spr_TblNewsletterGroup_GetTblNewsletterGroupByNewsletterGroupId";
        internal const string SPR_TBLNEWSLETTERGROUP_GETALLTBLNEWSLETTERGROUP = "spr_TblNewsletterGroup_GetAllTblNewsletterGroup";
        internal const string SPR_TBLNEWSLETTERGROUP_GETALLTBLNEWSLETTERGROUPPAGED = "spr_TblNewsletterGroup_GetAllTblNewsletterGroupPaged";
        internal const string SPR_TBLNEWSLETTERGROUP_GETALLTBLNEWSLETTERGROUPPAGEDCOUNT = "spr_TblNewsletterGroup_GetAllTblNewsletterGroupPagedCount";

        #endregion
    }
}
